//
//  WQTableViewController.m
//  lazyTableUpdate
//
//  Created by Bob Wu on 12-5-9.
//  Copyright (c) 2012年 veex. All rights reserved.
//


#import "WQTableViewController.h"

@implementation WQTableViewController


//load cell's image

- (void)loadCellImage
{
    NSArray *indexPathsForLoad = [wqTable indexPathsForVisibleRows];
    for (NSIndexPath *item in indexPathsForLoad) {
        if (item.row==tableDataArray.count) {
            return;
        }
        NSInteger rowNumberForCell = item.row;
        NSString *imageStr = [[tableDataArray objectAtIndex:rowNumberForCell] valueForKey:KimageKey];
        NSString *imageName =@"";
        if (![imageStr isEqual:[NSNull null] ]) {
            NSArray *array = [imageStr componentsSeparatedByString:@"/"];
            imageName = [array lastObject];
        }
        /*?inputPath=*/
        imageStr = [NSString stringWithFormat:@"%@%@",url_image, imageStr];

        if(imageName){
        NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:imageDataPath]) {
            
            NSURL *imageUrl = [NSURL URLWithString:[imageStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
            [imageData writeToFile:imageDataPath atomically:YES];
            UIImage *image = [UIImage imageWithData:imageData];
            [delegate cellImageDidLoad:item image:image];            
        }else{
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
            if (image) {
                [delegate cellImageDidLoad:item image:image];
            }
            else
            {
               image = [UIImage imageNamed:@"placeholder.png"];
                //placeholder为在未加载完成加载图片时显示的默认图片
                [delegate cellImageDidLoad:item image:image];
            }

        }
        }
    }
}

#pragma mark - Table View delegate
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!tableView.isDragging && !tableView.isDecelerating)
    {
        [self performSelectorInBackground:@selector(loadCellImage) withObject:nil];
    }
}

#pragma mark - Scroll View delegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self performSelectorInBackground:@selector(loadCellImage) withObject:nil];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate) {
        [self performSelectorInBackground:@selector(loadCellImage) withObject:nil];
    }
}

@end
